package com.zenith.user.controller;

import com.zenith.common.annotation.request.SecurePostMapping;
import com.zenith.common.result.Result;
import com.zenith.common.result.PageResult;
import com.zenith.user.po.domain.User;
import com.zenith.user.po.dto.UserDTO;
import com.zenith.user.po.vo.UserVO;
import com.zenith.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 用户管理
 *
 * @author makejava
 * @since 2025-08-15
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@Tag(name = "用户管理", description = "用户相关的CRUD操作")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @SecurePostMapping(value = "/createUser",roles = "ADMIN", permission = "user:create")
    @Operation(summary = "创建用户", description = "创建新的用户账户")
    public Result<String> createUser(
            @Valid @RequestBody UserDTO userDTO) {
        log.info("创建用户: {}", userDTO.getUsername());
        try {
            boolean result = userService.createUser(userDTO);
            if (result) {
                return Result.success("用户创建成功");
            } else {
                return Result.fail("用户创建失败");
            }
        } catch (Exception e) {
            log.error("创建用户异常", e);
            return Result.fail(e.getMessage());
        }
    }

    @SecurePostMapping(value = "/updateUser", roles = "ADMIN", permission = "user:update")
    @Operation(summary = "更新用户", description = "更新用户信息")
    public Result<String> updateUser(
            @Valid @RequestBody UserDTO userDTO) {
        log.info("更新用户: ID={}", userDTO.getId());
        try {
            boolean result = userService.updateUser(userDTO);
            if (result) {
                return Result.success("用户更新成功");
            } else {
                return Result.fail("用户更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户异常", e);
            return Result.fail(e.getMessage());
        }
    }

    @SecurePostMapping(value = "/deleteUser/{id}", roles = "ADMIN", permission = "user:delete")
    @Operation(summary = "删除用户", description = "逻辑删除指定的用户")
    public Result<String> deleteUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull Long id) {
        log.info("删除用户: ID={}", id);
        try {
            boolean result = userService.deleteUser(id);
            if (result) {
                return Result.success("用户删除成功");
            } else {
                return Result.fail("用户删除失败");
            }
        } catch (Exception e) {
            log.error("删除用户异常", e);
            return Result.fail(e.getMessage());
        }
    }

    @SecurePostMapping(value = "/getUserById/{id}", roles = "ADMIN", permission = "user:read")
    @Operation(summary = "获取用户详情", description = "根据ID查询用户详细信息")
    public Result<User> getUserById(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull Long id) {
        log.info("查询用户: ID={}", id);
        User user = userService.getUserById(id);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.fail("用户不存在");
        }
    }

    @SecurePostMapping(value = "/getUserByUsername", roles = "ADMIN", permission = "user:read")
    @Operation(summary = "按用户名查询", description = "根据用户名查询用户信息")
    public Result<User> getUserByUsername(
            @Parameter(description = "用户名", required = true)
            @RequestParam @NotBlank String username) {
        log.info("按用户名查询用户: {}", username);
        User user = userService.getUserByUsername(username);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.fail("用户不存在");
        }
    }

    @SecurePostMapping(value = "/getUserPage",roles = "ADMIN", permission = "user:read")
    @Operation(summary = "分页查询用户", description = "分页查询用户列表信息")
    public Result<PageResult<User>> getUserPage(
            @Valid @RequestBody UserDTO query) {
        log.info("分页查询用户: 第{}页, 每页{}条", query.getPageNum(), query.getPageSize());
        PageResult<User> pageResult = userService.getUserPage(query);
        return Result.success(pageResult);
    }

    @SecurePostMapping(value = "/getUsersByIds", roles = "ADMIN", permission = "user:read")
    @Operation(summary = "批量查询用户", description = "根据用户ID列表批量查询用户信息")
    public Result<List<UserVO>> getUsersByIds(
            @Parameter(description = "用户ID列表", required = true)
            @RequestBody @NotEmpty List<Long> ids) {
        log.info("批量查询用户: 数量={}", ids.size());
        List<UserVO> users = userService.getUsersByIds(ids);
        return Result.success(users);
    }

    @SecurePostMapping(value = "/updateUserStatus/{id}", roles = "ADMIN", permission = "user:update")
    @Operation(summary = "更新用户状态", description = "启用或禁用用户账户")
    public Result<String> updateUserStatus(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull Long id,
            @Parameter(description = "状态（1-正常 2-禁用）", required = true)
            @RequestParam @NotNull Integer status) {
        log.info("更新用户状态: ID={}, status={}", id, status);
        try {
            boolean result = userService.updateUserStatus(id, status);
            if (result) {
                return Result.success("用户状态更新成功");
            } else {
                return Result.fail("用户状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户状态异常", e);
            return Result.fail(e.getMessage());
        }
    }

    @SecurePostMapping(value = "/resetPassword/{id}",roles = "ADMIN", permission = "user:update")
    @Operation(summary = "重置密码", description = "重置指定用户的登录密码")
    public Result<String> resetPassword(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull Long id,
            @Parameter(description = "新密码", required = true)
            @RequestParam @NotBlank String newPassword) {
        log.info("重置用户密码: ID={}", id);
        try {
            boolean result = userService.resetPassword(id, newPassword);
            if (result) {
                return Result.success("密码重置成功");
            } else {
                return Result.fail("密码重置失败");
            }
        } catch (Exception e) {
            log.error("重置密码异常", e);
            return Result.fail(e.getMessage());
        }
    }


    @SecurePostMapping(value = "/saveOrUpdate", roles = {"ADMIN"}, permission = "user:write")
    @Operation(summary = "添加或修改用户（旧接口）")
    public Result<Void> saveOrUpdate(@RequestBody User entity) {
        log.info("添加或修改用户（旧接口）: {}", entity);
        userService.saveOrUpdate(entity);
        return Result.success();
    }

    @SecurePostMapping(value = "/deleteUsers", roles = {"ADMIN"}, permission = "user:delete")
    @Operation(summary = "批量删除用户（旧接口）")
    public Result<Void> deleteUsers(@RequestBody List<String> ids) {
        log.info("批量删除用户（旧接口）: {}", ids);
        userService.removeByIds(ids);
        return Result.success();
    }


    // =========================== 新增缺失接口 ===========================

    @SecurePostMapping(value = "/getCurrentUser",roles = "USER", permission = "user:read")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")
    public Result<UserVO> getCurrentUser(
            @Parameter(description = "用户ID", required = true)
            @RequestParam @NotNull Long userId) {
        log.info("获取当前用户信息: userId={}", userId);
        try {
            UserVO userVO = userService.getCurrentUserInfo(userId);
            if (userVO != null) {
                return Result.success(userVO);
            } else {
                return Result.fail("用户不存在");
            }
        } catch (Exception e) {
            log.error("获取当前用户信息异常", e);
            return Result.fail(e.getMessage());
        }
    }

    @SecurePostMapping(value = "/updateProfile",roles = "USER", permission = "user:update")
    @Operation(summary = "更新个人资料", description = "更新当前用户的个人资料")
    public Result<String> updateProfile(
            @Valid @RequestBody UserDTO userDTO) {
        log.info("更新个人资料: ID={}", userDTO.getId());
        try {
            boolean result = userService.updateUserProfile(userDTO);
            if (result) {
                return Result.success("个人资料更新成功");
            } else {
                return Result.fail("个人资料更新失败");
            }
        } catch (Exception e) {
            log.error("更新个人资料异常", e);
            return Result.fail(e.getMessage());
        }
    }

    @SecurePostMapping(value = "/changePassword",roles = "USER", permission = "user:update")
    @Operation(summary = "修改密码", description = "修改用户登录密码")
    public Result<String> changePassword(
            @Parameter(description = "用户ID", required = true)
            @RequestParam @NotNull Long userId,
            @Parameter(description = "原密码", required = true)
            @RequestParam @NotBlank String oldPassword,
            @Parameter(description = "新密码", required = true)
            @RequestParam @NotBlank String newPassword) {
        log.info("修改密码: userId={}", userId);
        try {
            boolean result = userService.changePassword(userId, oldPassword, newPassword);
            if (result) {
                return Result.success("密码修改成功");
            } else {
                return Result.fail("密码修改失败，请检查原密码");
            }
        } catch (Exception e) {
            log.error("修改密码异常", e);
            return Result.fail(e.getMessage());
        }
    }

    @SecurePostMapping(value = "/uploadAvatar",roles = "USER", permission = "user:update")
    @Operation(summary = "上传头像", description = "上传用户头像")
    public Result<String> uploadAvatar(
            @Parameter(description = "用户ID", required = true)
            @RequestParam @NotNull Long userId,
            @Parameter(description = "头像URL", required = true)
            @RequestParam @NotBlank String avatarUrl) {
        log.info("上传头像: userId={}, avatarUrl={}", userId, avatarUrl);
        try {
            boolean result = userService.updateAvatar(userId, avatarUrl);
            if (result) {
                return Result.success("头像上传成功");
            } else {
                return Result.fail("头像上传失败");
            }
        } catch (Exception e) {
            log.error("上传头像异常", e);
            return Result.fail(e.getMessage());
        }
    }

    @SecurePostMapping(value = "/batchAssignRoles", roles = "ADMIN", permission = "user:assign")
    @Operation(summary = "批量分配用户角色", description = "为多个用户批量分配角色")
    public Result<String> batchAssignRoles(
            @Parameter(description = "用户ID列表", required = true)
            @RequestParam @NotEmpty List<Long> userIds,
            @Parameter(description = "角色ID列表", required = true)
            @RequestParam @NotEmpty List<Long> roleIds) {
        log.info("批量分配用户角色: userIds={}, roleIds={}", userIds, roleIds);
        try {
            boolean result = userService.batchAssignRoles(userIds, roleIds);
            if (result) {
                return Result.success("批量分配角色成功");
            } else {
                return Result.fail("批量分配角色失败");
            }
        } catch (Exception e) {
            log.error("批量分配角色异常", e);
            return Result.fail(e.getMessage());
        }
    }

    @SecurePostMapping(value = "/searchUsers", roles = "ADMIN", permission = "user:search")
    @Operation(summary = "高级搜索用户", description = "按多条件搜索用户")
    public Result<PageResult<UserVO>> searchUsers(
            @Parameter(description = "搜索关键词")
            @RequestParam(required = false) String keyword,
            @Parameter(description = "状态")
            @RequestParam(required = false) Integer status,
            @Parameter(description = "角色")
            @RequestParam(required = false) String role,
            @Parameter(description = "页码")
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量")
            @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("高级搜索用户: keyword={}, status={}, role={}", keyword, status, role);
        try {
            PageResult<UserVO> result = userService.searchUsers(keyword, status, role, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            log.error("搜索用户异常", e);
            return Result.fail(e.getMessage());
        }
    }
}